package com.heepay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.heepay.common.HttpUtil;
import com.heepay.common.MyKey;
import com.heepay.common.SignEncrypt;
import org.bouncycastle.util.encoders.Base64;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.heepay.common.HttpUtil.parseJsonResponse;

/**
 *
 * 该接口为快捷签约查询接口，用于查询商户在快捷签约平台上已签约的银行卡信息和快捷签约码。
 *
 */
public class SignQuery {
    public static void main(String[] args) {
        try {
            String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            String method = "heepay.agreement.bank.sign.query";
            String version = "1.0";
            String merch_id = "1664502";
            String out_trade_no = "";

            // 业务参数组装
            JSONObject biz_content = new JSONObject();
            biz_content.put("out_trade_no", out_trade_no);

            // 签名串组装
            String OldSign = String.format("biz_content=%s&merch_id=%s&method=%s&timestamp=%s&version=%s",
                    biz_content.toJSONString(), merch_id, method, timestamp, version);
            System.out.println("签名串：--------->" + OldSign);

            // 获取私钥并加签
            PrivateKey privateKey = getPrivateKey(MyKey.privateKeystr);
            String sign = new SignEncrypt().sign(OldSign, privateKey);

            // 组装请求参数
            Map<String, String> map = new HashMap<>();
            map.put("biz_content", biz_content.toJSONString());
            map.put("merch_id", merch_id);
            map.put("method", method);
            map.put("timestamp", timestamp);
            map.put("version", version);
            map.put("sign", sign);
            String requestJson = JSON.toJSONString(map);
            System.out.println("最终请求参数--------->" + requestJson);

            // 发送请求
            String result = new HttpUtil().sendJsonHttpPost("https://Pay.Heepay.com/API/PageSign/Index.aspx", requestJson);
            System.out.println("响应结果--------->" + result);

            // 解析返回参数
            JsonNode jsonNode = parseJsonResponse(result);
            handleResponse(jsonNode, privateKey);

        } catch (Exception e) {
            System.err.println("发生错误：" + e.getMessage());
            e.printStackTrace();
        }
    }

    private static PrivateKey getPrivateKey(String privateKeyStr) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] privateKeyBytes = Base64.decode(privateKeyStr);
        return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
    }

    private static void handleResponse(JsonNode jsonNode, PrivateKey privateKey) {
        String sub_msg = jsonNode.get("sub_msg").asText();
        if ("签约成功".equals(sub_msg)) {
            String data = jsonNode.get("data").asText();
            try {
                String decryptedData = new SignEncrypt().decrypt(data, privateKey);
                JsonNode decryptedDataNode = parseJsonResponse(decryptedData);
                System.out.println("返回签约人信息--------->" + decryptedDataNode);
            } catch (Exception e) {
                System.err.println("解密失败：" + e.getMessage());
            }
        } else {
            System.out.println("输出失败sub_msg：--------->" + sub_msg);
        }
    }
}
